package com.anpxd.erpad.utils
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import com.anpxd.erpad.bean.BusTag
import com.lsxiao.apollo.core.Apollo
import com.socks.library.KLog
import java.util.*

/**
 * Created by xingyi on 2018/4/2.
 */
class BackHomeTimer private constructor()  {

    private var myTiemrTask: TimerTask? = null

    fun startTimer() {

        val task = object : TimerTask() {

            override fun run() {

                val message = Message()

                message.what = timeNum++

                handler.sendMessage(message)

            }
        }
        myTiemrTask = task
        timer.schedule(task,0,1000)
    }

    fun resetTime() {

        timeNum = 0

        Apollo.emit(BusTag.didResetTime)
    }

    fun cancelTimer() {

        timer.cancel()
        myTiemrTask?.cancel()
    }

    private var timeNum: Int = 0//记录当前多少秒没有操作

    private val maxTimeNum = 180//阈值

    companion object {
        fun getInstance() = Holder.INSTANCE
    }

    private object Holder {
        val INSTANCE = BackHomeTimer()
    }

    private val timer: Timer = Timer()

    private val handler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {

        override fun handleMessage(msg: Message) {
            KLog.w("xylog" ,timeNum)
            when (msg.what) {
                maxTimeNum -> {
                    timeNum = 0
                    Apollo.emit(BusTag.gotoHome)
                }
            }
            super.handleMessage(msg)
        }
    }
}